﻿using System.Transactions;
using dotnet.config;
using dotnet.entity;

namespace dotnet.service
{
    public class UserService(MyDbContext myDbContext)
    {
       private readonly MyDbContext _dbContext = myDbContext;

        public int SaveUser(string name,int age)
        {
            Random random = new();
            int randomNumber = random.Next(1, 10000000);
            User user = new() { Name = name+ randomNumber, Age = age+ randomNumber, CreateTime = DateTime.Now};
            using TransactionScope scope = new();
            int   result = 0;
            try
            {
                _dbContext.Users.Add(user);
                 result = _dbContext.SaveChanges();
                scope.Complete();
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex.Message);
            }
            finally
            {
                scope.Dispose();
            }

            return result;

        }

        public List<User> GetUsersPaged(int pageNumber=1, int pageSize=10)
        {
            return [.. _dbContext.Users
                          .OrderBy(u => u.CreateTime) // 确保有一个稳定的排序
                          .Skip((pageNumber - 1) * pageSize) // 跳过前面的页码
                          .Take(pageSize)]; // 执行查询并返回结果
        }
    
     }
}
